﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using StockTrader.API.TradingAlgos;
//using StockTrader.Broker.IciciDirect;
using StockTrader.Common;
using StockTrader.Core;
using StockTrader.Platform.Logging;
using StockTrader.Stocks.Utilities.Broker;
using StockTrader.Utilities;
using System.Globalization;

namespace StockTrader.UI.Trader
{
    public class OfflineAnalyzer : Form
    {
        [STAThread]
        public static void Main1()
        {
            // Start the application.
            OfflineAnalyzer chart = new OfflineAnalyzer();
            Application.Run(chart);
        }

        private Button button2;
        Thread workerThread;
        Thread workerThread1;
        private Button button3;
        private RichTextBox rtbLog;
        private Label label1;

        #region designer-generated-code
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series3 = new System.Windows.Forms.DataVisualization.Charting.Series();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.rtbLog = new System.Windows.Forms.RichTextBox();
            this.label1 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            // 
            // chart1
            // 
            this.chart1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.chart1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            this.chart1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            this.chart1.BackSecondaryColor = System.Drawing.Color.White;
            this.chart1.BorderlineColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            this.chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            this.chart1.BorderlineWidth = 2;
            this.chart1.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;
            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.IsClustered = true;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.Perspective = 10;
            chartArea1.Area3DStyle.Rotation = 10;
            chartArea1.Area3DStyle.WallWidth = 0;
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LabelStyle.Format = "ddMMM";
            chartArea1.AxisX.LabelStyle.Interval = 24D;
            chartArea1.AxisX.LabelStyle.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.Interval = 6D;
            chartArea1.AxisX.MajorGrid.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorTickMark.Interval = 6D;
            chartArea1.AxisX.MajorTickMark.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            chartArea1.AxisX.MajorTickMark.LineColor = System.Drawing.Color.CornflowerBlue;
            chartArea1.AxisX.MajorTickMark.Size = 2F;
            chartArea1.AxisX.ScrollBar.IsPositionedInside = false;
            chartArea1.AxisY.IsLabelAutoFit = false;
            chartArea1.AxisY.IsStartedFromZero = false;
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.Interval = 10D;
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MinorGrid.Interval = 5D;
            chartArea1.AxisY.ScrollBar.IsPositionedInside = false;
            chartArea1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(165)))), ((int)(((byte)(191)))), ((int)(((byte)(228)))));
            chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.InnerPlotPosition.Auto = false;
            chartArea1.InnerPlotPosition.Height = 85F;
            chartArea1.InnerPlotPosition.Width = 86F;
            chartArea1.InnerPlotPosition.X = 8.3969F;
            chartArea1.InnerPlotPosition.Y = 3.63068F;
            chartArea1.Name = "Default";
            chartArea1.Position.Auto = false;
            chartArea1.Position.Height = 86.76062F;
            chartArea1.Position.Width = 88F;
            chartArea1.Position.X = 5.089137F;
            chartArea1.Position.Y = 5.895753F;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            this.chart1.ChartAreas.Add(chartArea1);
            legend1.Alignment = System.Drawing.StringAlignment.Far;
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.DockedToChartArea = "Default";
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = false;
            legend1.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
            legend1.Name = "Default";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(12, 12);
            this.chart1.Name = "chart1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.ChartArea = "Default";
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series1.Legend = "Default";
            series1.Name = "Price";
            series1.ShadowOffset = 1;
            series2.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series2.BorderWidth = 3;
            series2.ChartArea = "Default";
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            series2.Color = System.Drawing.Color.Yellow;
            series2.Legend = "Default";
            series2.Name = "Peaks";
            series2.ShadowOffset = 1;
            series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
            series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series3.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series3.BorderWidth = 4;
            series3.ChartArea = "Default";
            series3.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            series3.Color = System.Drawing.Color.Green;
            series3.Legend = "Default";
            series3.Name = "Orders";
            series3.ShadowOffset = 1;
            series3.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
            series3.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            this.chart1.Series.Add(series1);
            this.chart1.Series.Add(series2);
            this.chart1.Series.Add(series3);
            this.chart1.Size = new System.Drawing.Size(381, 419);
            this.chart1.TabIndex = 13;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(290, 448);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(125, 40);
            this.button1.TabIndex = 1;
            this.button1.Text = "Start";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(437, 448);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(125, 40);
            this.button2.TabIndex = 14;
            this.button2.Text = "Pause";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // button3
            // 
            this.button3.Enabled = false;
            this.button3.Location = new System.Drawing.Point(584, 448);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(125, 40);
            this.button3.TabIndex = 15;
            this.button3.Text = "Reset";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // rtbLog
            // 
            this.rtbLog.Location = new System.Drawing.Point(415, 37);
            this.rtbLog.Name = "rtbLog";
            this.rtbLog.ReadOnly = true;
            this.rtbLog.Size = new System.Drawing.Size(637, 394);
            this.rtbLog.TabIndex = 16;
            this.rtbLog.Text = "";
            this.rtbLog.WordWrap = false;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(412, 12);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(25, 13);
            this.label1.TabIndex = 17;
            this.label1.Text = "Log";
            // 
            // OfflineAnalyzer
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1064, 500);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.rtbLog);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.chart1);
            this.Name = "OfflineAnalyzer";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.OfflineAnalyzer_Load);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        private System.Windows.Forms.Button button1;
        #endregion

        IBroker _iciciDirectAccount;
        //IciciDirectBroker _iciciDirectAccount;
        object _logSyncRoot = new object();
        Queue<string> _logMsgQ = new Queue<string>();
        System.Threading.Timer _logTimer;
        public int DaysToAnalyze = -50;
        public bool IsAutoStart = false;

        public OfflineAnalyzer()
        {
            InitializeComponent();

            SetupChart();

            _iciciDirectAccount = null;

            AlgoRunUtils.EventResetChart += new ResetChartHandler(ResetChart);

            _resetChart = ResetChart;

            TimeSpan dueTime = new TimeSpan(0, 0, 0);
            TimeSpan period = new TimeSpan(0, 0, 2);
            //TimerCallback tc = new TimerCallback(ActualAppendLog);
            //_logTimer = new System.Threading.Timer(ActualAppendLog, null, dueTime, period);
        }

        private void OfflineAnalyzer_Load(object sender, EventArgs e)
        {
            if (IsAutoStart)
                new Thread(() => { Start(); }).Start();
        }

        private void Start()
        {
            button1_Click(null, null);
        }

        public ResetChartHandler _resetChart;

        public void AddDataPoint(ChartTickPoint d)
        {
            return;
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<ChartTickPoint>(this.AddDataPoint), new object[] { d });
            }
            else
            {
                if (d.TickType == ChartTickType.Price)
                {
                    chart1.Series[0].Points.AddXY(d.X, d.Y);
                }
                else if (d.TickType == ChartTickType.SquareOffPoint)
                {
                    Series series = chart1.Series[1];
                    Color pointColor;
                    if (d.IsBuyOrderOrBottomPeak)
                    {
                        pointColor = Color.Fuchsia;
                    }
                    else
                    {
                        pointColor = Color.Fuchsia;
                    }

                    series.Points.AddXY(d.X, d.Y);

                    series.Points[series.Points.Count - 1].Color = pointColor;
                }
                else if (d.TickType == ChartTickType.Peak)
                {
                    Series series = chart1.Series[1];
                    Color pointColor;
                    if (d.IsBuyOrderOrBottomPeak)
                    {
                        pointColor = Color.White;
                    }
                    else
                    {
                        pointColor = Color.White;
                    }

                    series.Points.AddXY(d.X, d.Y);

                    series.Points[series.Points.Count - 1].Color = pointColor;
                }
                else
                {
                    Series series = chart1.Series[2];
                    Color pointColor;
                    if (d.IsBuyOrderOrBottomPeak)
                    {
                        pointColor = Color.Green;
                    }
                    else
                    {
                        pointColor = Color.Orange;
                    }
                    series.Points.AddXY(d.X, d.Y);
                    series.Points[series.Points.Count - 1].Color = pointColor;
                }
            }
        }

        int _threadsCompleted = 0;


        public void AppendLog1(string message)
        {
            try
            {
                lock (_logSyncRoot)
                {
                    _logMsgQ.Enqueue(message);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        // NOT USED CURRENTLY
        public void ActualAppendLog(object state)
        {
            try
            {
                //return;
                if (rtbLog.InvokeRequired)
                {
                    rtbLog.Invoke(new Action<string>(this.ActualAppendLog), state);
                }
                else
                {
                    lock (_logSyncRoot)
                    {
                        while (_logMsgQ.Count > 0)
                        {
                            string message = _logMsgQ.Dequeue();

                            if (message.Contains("completed !! at Time"))
                                _threadsCompleted++;

                            rtbLog.AppendText(message);

                            if (rtbLog.TextLength % 10000 == 0)
                                rtbLog.ScrollToCaret();

                            if (rtbLog.TextLength > 100000)
                                rtbLog.ResetText();
                        }
                    }

                    if (_threadsCompleted >= 2)
                    {
                        _threadsCompleted = 0;
                        int timeout = 0;
                        DialogResult result = MessageBox.Show("Completed!!");
                        while (timeout++ < 30 || result == DialogResult.OK)
                            Thread.Sleep(1000);
                        Environment.Exit(0);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        public void AppendLog(string message)
        {
            try
            {
                //return;
                if (rtbLog.InvokeRequired)
                {
                    rtbLog.Invoke(new Action<string>(this.AppendLog), message);
                }
                else
                {
                    lock (_logSyncRoot)
                    {
                        if (message.Contains("completed !! at Time"))
                            _threadsCompleted++;

                        rtbLog.AppendText(message);

                        if (rtbLog.TextLength % 10000 == 0)
                            rtbLog.ScrollToCaret();

                        if (rtbLog.TextLength > 100000)
                            rtbLog.ResetText();
                    }

                    if (_threadsCompleted >= 2)
                    {
                        _threadsCompleted = 0;
                        if(!IsAutoStart)
                            MessageBox.Show("Completed!!");
                        else
                            Thread.Sleep(5000);
                        Application.Exit();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var fileDateDgb = "";
            try
            {
                if ((workerThread == null && workerThread1 == null) ||
                    (workerThread.ThreadState == ThreadState.Stopped && workerThread1.ThreadState == ThreadState.Stopped))
                {
                    string traceFileName = "ST-QA-" + DateTime.Today.ToString("yyyyMMdd") + "-" + DateTime.Now.ToString("HHmm");
                    StockTrader.Platform.Logging.FileTracing.SetTraceFilename(SystemUtils.GetStockRunTempLocation(), traceFileName);

                    bool isMock = true;
                    bool isReplay = true;
                    bool useProbableTradeValue = false;
                    bool isForceUpdate = true;
                    bool isHedgeAlgo = true;

                    //DaysToAnalyze = -25;
                    DateTime allowTicksOnOrAfterDate = DateTime.Now.AddDays(DaysToAnalyze);

                    TickFormatType tickFormat = TickFormatType.OnlyLTP;
                    string R1 = "2012";
                    string R2 = "Algo-Test";

                    //r2 = "GOLD";
                    string stocksDir;
                    //stocksDir = @"H:\StockData\6month-IEOD-Data-Original\20090521";
                    //stocksDir = @"H:\StockData\1Parshant-Global-data\1-minute-indices-short";
                    stocksDir = @"H:\StockData\1Parshant-Global-data\1-minute-indian-futures-myformat";
                    stocksDir = @"H:\StockData\1QA-1min-Fut-Data\Test";
                    stocksDir = @"C:\StockTest\Indices";
                    stocksDir = @"C:\StockRunFiles\TickFiles";
                    //stocksDir = @"C:\StockTest\QA";
                    //stocksDir = @"C:\StockRunFiles\Google\1d";

                    //stocksDir = @"H:\StockData\6month-IEOD-Data-MyFormat";

                    //var yearsDir = Directory.EnumerateDirectories(stocksDir, "*");

                    int fileSizeThreshold = 5000;

                    List<TickFileMetadata> t1 = new List<TickFileMetadata>();
                    List<TickFileMetadata> t2 = new List<TickFileMetadata>();

                    int fileTypeCode = 0;  //mockfiles = 0, google files = 1, old data = 2, gold = 3
                    for (; fileTypeCode <= 0; fileTypeCode++)
                    {
                        int cnt = 0;
                        int numStocks = 0;

                        if (fileTypeCode == 0)
                            stocksDir = @"C:\StockRunFiles\TickFiles";
                        //stocksDir = @"C:\StockRunFiles\Test";
                        else
                            stocksDir = @"C:\StockRunFiles\Google\1d";

                        //string pattern = "*300412*";
                        ////if(fileTypeCode == 0)
                        //    pattern = "*";

                        var stocks1 = Directory.EnumerateFiles(stocksDir, "*", SearchOption.AllDirectories);

                        var stocks = new List<string>(stocks1);

                        foreach (var stock in stocks)
                            numStocks++;

                        // order by size asc
                        //var fileSizeMap = new SortedDictionary<long, string>();
                        //foreach (string filePath in stocks)
                        //{
                        //    FileInfo fi = new FileInfo(filePath);
                        //    fileSizeMap.Add(fi.Length, filePath);
                        //}
                        //stocks = fileSizeMap.Values.ToList();

                        HashSet<string> set = new HashSet<string>();
                        //HashSet<string> set1 = new HashSet<string>(new string[] { "CNXBAN", "NIFTY", "STABAN", "MINIFT", "YESBAN", "BAAUTO", "RELIND" });
                        HashSet<string> set1 = new HashSet<string>(new string[] { "NIFTY" });//, "CNXBAN", "MINIFT"});

                        foreach (string filePath in stocks)
                        {
                            var splitPath = Path.GetDirectoryName(filePath).Split(Path.DirectorySeparatorChar);

                            var r2 = "IEOD-1min";
                            var r1 = splitPath[splitPath.Length - 1];

                            var fileDateStr = fileDateDgb = r1.Insert(2, "-").Insert(5, "-");
                            CultureInfo provider = CultureInfo.InvariantCulture;
                            DateTime fileDate;

                            if (fileDateStr.Length == 8)
                                DateTime.TryParseExact(fileDateStr, "dd-mm-yy", provider, out fileDate);
                            else
                                DateTime.TryParseExact(fileDateStr, "dd-mm-yyyy", provider, out fileDate);

                            if (fileDate < allowTicksOnOrAfterDate)
                                continue;

                            if (!MarketUtils.IsTimeAfter330Market() && fileDate.Date == DateTime.Now.Date) continue;
                            //fileSizeThreshold = r1 == "2010" ? 500 : 1200;
                            //r1 = "Indices";
                            //FileInfo fi = new FileInfo(filePath);
                            //if (fi.Length < fileSizeThreshold * 1024) continue;

                            string stockName = Path.GetFileName(filePath);
                            stockName = stockName.Remove(stockName.IndexOf('.')); // Remove extension



                            switch (fileTypeCode)
                            {
                                case 0:
                                    // **************** for mock collected data *********************
                                    if (MarketUtils.IsMarketOpen() && r1 == DateTime.Now.Date.ToString("ddMMyyyy")) continue;
                                    tickFormat = TickFormatType.Custom;

                                    //r1 = fi.Length.ToString();
                                    if (stockName.Contains("FUT-"))
                                        stockName = stockName.Replace("FUT-", "");

                                    if (!stockName.Contains("OPT-"))
                                    {
                                        if (stockName.Contains('-'))
                                            stockName = stockName.Remove(stockName.IndexOf('-')); // just get the symbol for collected mock tick files


                                        r2 = "Algo-Test1";

                                        //continue;
                                    }
                                    else
                                    {
                                        if (stockName.Contains('-'))
                                            stockName = stockName.Remove(stockName.LastIndexOf('-')); // remove time
                                        if (stockName.Contains("-Q") && stockName.Contains('-'))
                                            stockName = stockName.Remove(stockName.LastIndexOf('-')); // remove qty

                                        r2 = "Algo-Test4";
                                        continue;
                                    }

                                    if (stockName.Contains('_'))
                                        stockName = stockName.Remove(stockName.IndexOf('_')); // just get the symbol for collected mock tick files

                                    if (!set1.Contains(stockName))
                                        continue;
                                    //if (stockName != "NIFTY") continue;

                                    if (set.Contains(stockName + r1))
                                        continue;
                                    else set.Add(stockName + r1);

                                    // **************** for mock collected data *********************
                                    break;

                                case 1:
                                    r2 = "Algo-Test3";
                                    tickFormat = TickFormatType.OnlyLTP;

                                    if (stockName.Contains('-'))
                                        stockName = stockName.Remove(stockName.IndexOf('-')); // just get the symbol for collected mock tick files
                                    //if (stockName != "JPASSOCIAT") continue;
                                    if (set.Contains(stockName + r1))
                                        continue;
                                    else set.Add(stockName + r1);

                                    break;

                                case 2:
                                    if (stockName.Contains("IEOD"))
                                    {
                                        stockName = stockName.Remove(stockName.Length - 5); // Remove -IEOD\
                                        r2 = "IEOD-1sec";
                                    }
                                    else if (stockName.Contains("EOD"))
                                    {
                                        stockName = stockName.Remove(stockName.Length - 4); // Remove -EOD
                                        r2 = "EOD";
                                    }

                                    r2 = "Algo-Test2";
                                    //else if(Path.GetExtension(filePath) == ".csv")
                                    break;

                            }

                            if (isHedgeAlgo)
                                r2 = "Algo-Hedge1";

                            if (cnt++ % 2 == 0)
                                t1.Add(new TickFileMetadata { Path = filePath, Symbol = stockName, R1 = r1, R2 = r2, TickFormatType = tickFormat });
                            else
                                t2.Add(new TickFileMetadata { Path = filePath, Symbol = stockName, R1 = r1, R2 = r2, TickFormatType = tickFormat });

                        }
                    }

                    // Set Algo Params
                    AlgoParams algoParams = new AlgoParams();
                    //Params.r1 = r1;
                    //Params.r2 = r1;
                    algoParams.IsMock = isMock;
                    algoParams.IsReplayMode = isReplay;
                    algoParams.ReplayTickFile = @"D:\StockData\NIFTY-5Oct2005-7Apr2006-10000ticks.txt";
                    algoParams.PositionsFile = @"D:\StockData\NIFTY_positions1.txt";
                    //Params.algoId = -1;
                    algoParams.UseProbableTradeValue = useProbableTradeValue;
                    algoParams.IsMarketClosingSquareOff = true;
                    //Params.isSquareOffTrigger = false;
                    //Params.isMinProfitMust = false;
                    //Params.percMarketDirectionChange = 0;
                    //Params.percSquareOffThreshold = 0;
                    //Params.percStoploss = 0;
                    //Params.percMinProfit = 0;
                    //Params.allowShort = true;
                    //Params.allowLong = true;
                    //Params.startOrders = null;
                    algoParams.Broker = _iciciDirectAccount;
                    //Params.stockCode = null;
                    algoParams.MaxTotalPositions = 1;
                    algoParams.MaxLongPositions = 1;
                    algoParams.MaxShortPositions = 1;
                    algoParams.LongCeilingPrice = 100000;
                    algoParams.ShortFloorPrice = 0.01;
                    algoParams.PercPositionSpacing = 0.01;
                    algoParams.PercBrokerage = 0.08;
                    algoParams.SquareOffBrokerageFactor = 1.4;
                    algoParams.MarginFraction = 0.25;
                    //algoParams.AlgoId = 2;
                    algoParams.AlgoIntervalInSeconds = 0;

                    algoParams.IsHedgeAlgo = isHedgeAlgo;
                    //algoParams.IsSingleTradePerDay = true;
                    //algo

                    var start = new DateTime(2009, 5, 1);
                    var end = new DateTime(2009, 5, 30);

                    var algoData = new AlgoMetadata(t1,
                                                 start, end, algoParams, isForceUpdate,
                                                 AddDataPoint, null,
                                                 AppendLog);

                    var iciciAccObj = new BrokingAccountObject(_iciciDirectAccount) { CustomData = algoData, CustomData2 = null };

                    var algoData1 = new AlgoMetadata(t2,
                                                start, end, algoParams, isForceUpdate,
                                                AddDataPoint, null,
                                                AppendLog);

                    var iciciAccObj1 = new BrokingAccountObject(_iciciDirectAccount) { CustomData = algoData1, CustomData2 = null };

                    workerThread = new Thread(() =>
                    {
                        var a = new AlgoRunUtils(); a.RunAlgos(iciciAccObj);
                    });
                    workerThread1 = new Thread(() =>
                    {
                        var a = new AlgoRunUtils(); a.RunAlgos(iciciAccObj1);
                    });

                    workerThread.Start();
                    workerThread1.Start();

                    //var tmpPath = SystemUtils.GetStockRunTempLocation();
                    //if (Directory.Exists(tmpPath))
                    //    Directory.Delete(tmpPath, true);
                }
                else
                {
                    //ResetChart(null, null);
                    workerThread.Resume();
                    workerThread1.Resume();
                }
            }
            catch (Exception ex)
            {
                FileTracing.TraceOut("Exception: " + ex);
            }
        }

        private void worker(object obj)
        {
            Random rand = new Random();
            DateTime dt = DateTime.Now;// DateTime.Now.AddYears(-7);
            var _delegate = (Action<myData>)obj;
            for (int x = 0; x < 500; x++)
            {
                //dt = dt.AddMinutes(x);
                _delegate(new myData { X = dt.AddMinutes(x), Y = rand.Next(2000, 6000) });
                Thread.Sleep(1000);
            }
        }
        private void SetupChart()
        {
            //chart1.ChartAreas[0].AxisX.Minimum = DateTime.Now.AddYears(-7).ToOADate();
            //chart1.ChartAreas[0].AxisX.Maximum = DateTime.Now.ToOADate();
            //chart1.ChartAreas[0].AxisY.Minimum = 2000;
            //chart1.ChartAreas[0].AxisY.Maximum = 6000;

            // 
            // chart1
            // 
            //this.chart1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            //            | System.Windows.Forms.AnchorStyles.Left)
            //            | System.Windows.Forms.AnchorStyles.Right)));
            //this.chart1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            //this.chart1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //this.chart1.BackSecondaryColor = System.Drawing.Color.White;
            //this.chart1.BorderlineColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            //this.chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            //this.chart1.BorderlineWidth = 2;
            //this.chart1.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            ChartArea chartArea2 = this.chart1.ChartAreas[0];

            // Cursors
            System.Windows.Forms.DataVisualization.Charting.Cursor cursorX = chartArea2.CursorX;
            System.Windows.Forms.DataVisualization.Charting.Cursor cursorY = chartArea2.CursorY;

            cursorX.IsUserEnabled = true;
            cursorX.IsUserSelectionEnabled = true;

            cursorY.IsUserEnabled = true;
            cursorY.IsUserSelectionEnabled = true;

            //chartArea2.Area3DStyle.Inclination = 15;
            //chartArea2.Area3DStyle.IsClustered = true;
            //chartArea2.Area3DStyle.IsRightAngleAxes = false;
            //chartArea2.Area3DStyle.Perspective = 10;
            //chartArea2.Area3DStyle.Rotation = 10;
            //chartArea2.Area3DStyle.WallWidth = 0;
            //chartArea2.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //chartArea2.AxisX.LabelStyle.Format = "ddMMM";
            //chartArea2.AxisX.LabelStyle.Interval = 24D;
            //chartArea2.AxisX.LabelStyle.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            //chartArea2.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            //chartArea2.AxisX.MajorGrid.Interval = 6D;
            //chartArea2.AxisX.MajorGrid.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            //chartArea2.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            //chartArea2.AxisX.MajorTickMark.Interval = 6D;
            //chartArea2.AxisX.MajorTickMark.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
            //chartArea2.AxisX.MajorTickMark.LineColor = System.Drawing.Color.CornflowerBlue;
            //chartArea2.AxisX.MajorTickMark.Size = 2F;
            //chartArea2.AxisX.ScrollBar.IsPositionedInside = false;
            //chartArea2.AxisY.IsLabelAutoFit = false;
            //chartArea2.AxisY.IsStartedFromZero = false;
            //chartArea2.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //chartArea2.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            //chartArea2.AxisY.MajorGrid.Interval = 10D;
            //chartArea2.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            //chartArea2.AxisY.MinorGrid.Interval = 5D;
            //chartArea2.AxisY.ScrollBar.IsPositionedInside = false;
            //chartArea2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(165)))), ((int)(((byte)(191)))), ((int)(((byte)(228)))));
            //chartArea2.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea2.BackSecondaryColor = System.Drawing.Color.White;
            //chartArea2.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            //chartArea2.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            //chartArea2.InnerPlotPosition.Auto = false;
            //chartArea2.InnerPlotPosition.Height = 85F;
            //chartArea2.InnerPlotPosition.Width = 86F;
            //chartArea2.InnerPlotPosition.X = 8.3969F;
            //chartArea2.InnerPlotPosition.Y = 3.63068F;
            //chartArea2.Name = "Default";
            //chartArea2.Position.Auto = false;
            //chartArea2.Position.Height = 86.76062F;
            //chartArea2.Position.Width = 88F;
            //chartArea2.Position.X = 5.089137F;
            //chartArea2.Position.Y = 5.895753F;
            //chartArea2.ShadowColor = System.Drawing.Color.Transparent;
            //this.chart1.ChartAreas.Add(chartArea2);
            //this.chart1.Location = new System.Drawing.Point(12, 12);
            //this.chart1.Name = "chart1";



            //legend2.Alignment = System.Drawing.StringAlignment.Far;
            //legend2.BackColor = System.Drawing.Color.Transparent;
            //legend2.DockedToChartArea = "Default";
            //legend2.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
            //legend2.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //legend2.IsTextAutoFit = false;
            //legend2.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
            //legend2.Name = "Default";
            //this.chart1.Legends.Add(legend2);

            //series4.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            //series4.ChartArea = "Default";
            //series4.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            //series4.Color = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            //series4.Legend = "Default";
            //series4.Name = "Price";
            //series4.ShadowOffset = 1;
            //series5.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            //series5.BorderWidth = 3;
            //series5.ChartArea = "Default";
            //series5.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            //series5.Color = System.Drawing.Color.Yellow;
            //series5.Legend = "Default";
            //series5.Name = "Peaks";
            //series5.ShadowOffset = 1;
            //series5.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
            //series5.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            //series6.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            //series6.BorderWidth = 4;
            //series6.ChartArea = "Default";
            //series6.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            //series6.Color = System.Drawing.Color.Green;
            //series6.Legend = "Default";
            //series6.Name = "Orders";
            //series6.ShadowOffset = 1;
            //series6.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
            //series6.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            //this.chart1.Series.Add(series4);
            //this.chart1.Series.Add(series5);
            //this.chart1.Series.Add(series6);

            //this.chart1.Size = new System.Drawing.Size(1008, 419);
            //this.chart1.TabIndex = 13;
        }


        private void ResetChart(object o, EventArgs e)
        {
            return;
            // Predefine the viewing area of the chart
            //minValue = DateTime.Now;
            //maxValue = minValue.AddSeconds(30);

            //chart1.ChartAreas[0].AxisX.Minimum = minValue.ToOADate();
            //chart1.ChartAreas[0].AxisX.Maximum = maxValue.ToOADate();
            if (this.InvokeRequired)
            {
                this.Invoke(_resetChart, new object[] { o, e });
            }
            else
            {
                //chart1.Series.Clear();

                //System.Windows.Forms.DataVisualization.Charting.Series series4 = new System.Windows.Forms.DataVisualization.Charting.Series();
                //System.Windows.Forms.DataVisualization.Charting.Series series5 = new System.Windows.Forms.DataVisualization.Charting.Series();
                //System.Windows.Forms.DataVisualization.Charting.Series series6 = new System.Windows.Forms.DataVisualization.Charting.Series();

                //series4.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
                //series4.ChartArea = "Default";
                //series4.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                //series4.Color = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
                //series4.Legend = "Default";
                //series4.Name = "Price";
                //series4.ShadowOffset = 1;
                //series5.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
                //series5.BorderWidth = 3;
                //series5.ChartArea = "Default";
                //series5.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
                //series5.Color = System.Drawing.Color.Yellow;
                //series5.Legend = "Default";
                //series5.Name = "Peaks";
                //series5.ShadowOffset = 1;
                //series5.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
                //series5.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
                //series6.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
                //series6.BorderWidth = 4;
                //series6.ChartArea = "Default";
                //series6.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
                //series6.Color = System.Drawing.Color.Green;
                //series6.Legend = "Default";
                //series6.Name = "Orders";
                //series6.ShadowOffset = 1;
                //series6.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
                //series6.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
                //this.chart1.Series.Add(series4);
                //this.chart1.Series.Add(series5);
                //this.chart1.Series.Add(series6);

                //this.chart1.Invalidate();


                // Reset number of series in the chart.
                foreach (Series s in chart1.Series)
                {
                    s.Points.Clear();
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            workerThread.Suspend();
            workerThread1.Suspend();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            ResetChart(null, null);
        }

    }
    public class myData
    {
        public DateTime X;
        public double Y;
    }
}